import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { ChatSession, Contact, Message } from './type'

export const useChatStore = defineStore('chat', () => {
  // 聊天会话列表
  const sessions = ref<ChatSession[]>([])

  // 当前激活的聊天会话
  const activeSessionId = ref<string | null>(null)

  // 联系人列表
  const contacts = ref<Contact[]>([])

  // 消息列表（按会话ID分组）
  const messages = ref<Map<string, Message[]>>(new Map())

  // 当前激活的会话
  const activeSession = computed(
    () => sessions.value.find((s) => s.id === activeSessionId.value) || null
  )

  // 当前聊天的消息列表
  const currentMessages = computed(() => {
    if (!activeSessionId.value) return []
    return messages.value.get(activeSessionId.value) || []
  })

  // 总未读消息数
  const totalUnreadCount = computed(() =>
    sessions.value.reduce((total, session) => total + session.unreadCount, 0)
  )

  // 设置激活会话
  const setActiveSession = (sessionId: string): void => {
    activeSessionId.value = sessionId
    // 标记为已读
    const session = sessions.value.find((s) => s.id === sessionId)
    if (session) {
      session.unreadCount = 0
    }
  }

  // 添加消息
  const addMessage = (sessionId: string, message: Message): void => {
    if (!messages.value.has(sessionId)) {
      messages.value.set(sessionId, [])
    }
    messages.value.get(sessionId)?.push(message)

    // 更新会话最后消息
    const session = sessions.value.find((s) => s.id === sessionId)
    if (session) {
      session.lastMessage = message
      session.lastActiveTime = message.timestamp
      if (sessionId !== activeSessionId.value) {
        session.unreadCount += 1
      }
    }
  }

  // 发送消息
  const sendMessage = (content: string, type: Message['type'] = 'text'): void => {
    if (!activeSessionId.value) return

    const message: Message = {
      id: Date.now().toString(),
      senderId: 'current-user', // 应该从用户store获取
      receiverId: activeSessionId.value,
      content,
      type,
      timestamp: new Date(),
      status: 'sending'
    }

    addMessage(activeSessionId.value, message)

    // TODO: 发送到服务器
    setTimeout(() => {
      message.status = 'sent'
    }, 1000)
  }

  // 创建新会话
  const createSession = (contactId: string): ChatSession | undefined => {
    const contact = contacts.value.find((c) => c.id === contactId)
    if (!contact) return

    const session: ChatSession = {
      id: contactId,
      type: 'private',
      name: contact.nickname,
      avatar: contact.avatar,
      unreadCount: 0,
      lastActiveTime: new Date(),
      participants: ['current-user', contactId]
    }

    addSession(session)
    setActiveSession(contactId)
    return session
  }

  // 删除会话
  const removeSession = (sessionId: string): void => {
    const index = sessions.value.findIndex((s) => s.id === sessionId)
    if (index !== -1) {
      sessions.value.splice(index, 1)
    }

    // 清除消息
    messages.value.delete(sessionId)

    // 如果删除的是当前激活会话，清除激活状态
    if (activeSessionId.value === sessionId) {
      activeSessionId.value = null
    }
  }

  // 标记消息为已读
  const markMessagesAsRead = (sessionId: string): void => {
    const session = sessions.value.find((s) => s.id === sessionId)
    if (session) {
      session.unreadCount = 0
    }
  }

  // 搜索会话
  const searchSessions = (keyword: string): ChatSession[] => {
    if (!keyword.trim()) return sessions.value

    return sessions.value.filter((session) =>
      session.name.toLowerCase().includes(keyword.toLowerCase())
    )
  }

  // 搜索联系人
  const searchContacts = (keyword: string): Contact[] => {
    if (!keyword.trim()) return contacts.value

    return contacts.value.filter(
      (contact) =>
        contact.nickname.toLowerCase().includes(keyword.toLowerCase()) ||
        contact.username.toLowerCase().includes(keyword.toLowerCase())
    )
  }

  // 添加联系人
  const addContact = (contact: Contact): void => {
    const existingIndex = contacts.value.findIndex((c) => c.id === contact.id)
    if (existingIndex >= 0) {
      contacts.value[existingIndex] = contact
    } else {
      contacts.value.push(contact)
    }
  }

  // 添加会话
  const addSession = (session: ChatSession): void => {
    const existingIndex = sessions.value.findIndex((s) => s.id === session.id)
    if (existingIndex >= 0) {
      sessions.value[existingIndex] = session
    } else {
      sessions.value.push(session)
    }
  }

  // 初始化模拟数据 - 现在只是一个空壳，实际数据由mock/examples.ts提供
  const initMockData = async (): Promise<void> => {
    console.log('使用自定义mock数据进行初始化')
    try {
      // 导入自定义mock数据
      const { initializeWithMockData } = await import('@/mock/examples')
      await initializeWithMockData()
    } catch (error) {
      console.error('加载自定义mock数据失败，请检查mock/examples.ts文件:', error)
    }
  }

  // 清空联系人列表
  const clearContacts = (): void => {
    contacts.value = []
    // 可能也需要清空相关的会话和消息
    sessions.value = []
    messages.value = new Map()
    activeSessionId.value = null
  }

  // 更新消息状态
  const updateMessageStatus = (messageId: string, status: Message['status']): void => {
    messages.value.forEach((messageList) => {
      const message = messageList.find((msg) => msg.id === messageId)
      if (message) {
        message.status = status
      }
    })
  }

  return {
    sessions,
    activeSessionId,
    contacts,
    messages,
    activeSession,
    currentMessages,
    totalUnreadCount,
    setActiveSession,
    addMessage,
    sendMessage,
    addContact,
    addSession,
    createSession,
    removeSession,
    markMessagesAsRead,
    searchSessions,
    searchContacts,
    clearContacts,
    updateMessageStatus,
    initMockData
  }
})
